package leetcode.segmentTree.p307;

import java.util.Arrays;


/**
 * 
 * @Title: NumArray.java 
 * @Package leetcode.segmentTree.p307 
 * @Description: 307. 区域和检索 - 数组可修改
 *                  使用线段树求解
 * @author CandyWall   
 * @date 2021年1月10日 下午2:34:19 
 * @version V1.0
 */
public class NumArray_v2 {
    // 线段树父节点如何融合左右孩子节点的值
    public interface Merger<E> {
        E merge(E a, E b);
    }
    public class SegmentTree<E> {
        private E[] data;
        private E[] tree;
        private Merger<E> merger;
        
        public void setMerger(Merger merger) {
            this.merger = merger;
        }
        
        public SegmentTree(E[] arr, Merger merger) {
            this.merger = merger;
            data = Arrays.copyOf(arr, arr.length);
            /*data = (E[]) new Object[arr.length];
            for(int i = 0; i < arr.length; i++) {
                data[i] = arr[i];
            }*/
            
            tree = (E[]) new Object[4 * arr.length];
            buildSegmentTree(0, 0, data.length - 1);
        }
        
        public SegmentTree(E[] arr) {
            this(arr, null);
        }
        
        // 在treeIndex的位置创建表示区间[l...r]的线段树
        private void buildSegmentTree(int treeIndex, int l, int r) {
            if(l == r) {
                tree[treeIndex] = data[l];
                return;
            }
            
            int leftTreeIndex = getLeftChildIndex(treeIndex);
            int rightTreeIndex = getRightChildIndex(treeIndex);
            
            //int mid = l + (r - l) / 2;
            int mid = l + ((r - l) >> 1);
            buildSegmentTree(leftTreeIndex, l, mid);
            buildSegmentTree(rightTreeIndex, mid + 1, r);
            
            // tree[treeIndex] = tree[leftTreeIndex] + tree[rightTreeIndex];
            if(merger != null) {
                tree[treeIndex] = merger.merge(tree[leftTreeIndex], tree[rightTreeIndex]);
            }
        }

        /**
         * 校验待操作的数组下标是否合法
         */
        private void checkArrayIndexRange(int index) {
            if(index >= data.length || index < 0) {
                throw new IllegalArgumentException("索引index不合法！");
            }
        }
        
        public E get(int index) {
            checkArrayIndexRange(index);
            return data[index];
        }
        
        public int getSize() {
            return data.length;
        }
        
        // 在完全二叉树表示中，根据父节点的索引，获取左孩子节点的索引
        private int getLeftChildIndex(int parentIndex) {
            return parentIndex * 2 + 1;
        }
        
        // 在完全二叉树表示中，根据父节点的索引，获取右孩子节点的索引
        private int getRightChildIndex(int parentIndex) {
            return parentIndex * 2 + 2;
        }
        
        // 返回区间[l, r]的值
        public E query(int queryL, int queryR) {
            checkArrayIndexRange(queryL);
            checkArrayIndexRange(queryR);
            if(queryL > queryR) {
                throw new IllegalArgumentException("索引index不合法！");
            }
            return query(0, 0, data.length - 1, queryL, queryR);
        }
        
        // 在treeIndex为根的线段树[l...r]的范围里，搜索区间[queryL...queryR]的值
        private E query(int treeIndex, int l, int r, int queryL, int queryR) {
            if(l == queryL && r == queryR) {
                return tree[treeIndex];
            }
            
            int mid = l + ((r - l) >> 1);
            int leftChildIndex = getLeftChildIndex(treeIndex);
            int rightChildIndex = getRightChildIndex(treeIndex);
            if(queryR <= mid) {
                return query(leftChildIndex, l, mid, queryL, queryR);
            }
            else if(queryL >= mid + 1) {
                return query(rightChildIndex, mid + 1, r, queryL, queryR);
            }
            
            E leftResult = query(leftChildIndex, l, mid, queryL, mid);
            E rightResult = query(rightChildIndex, mid + 1, r, mid + 1, queryR);
            return merger.merge(leftResult, rightResult);
        }
        
        // 将索引为index处的值修改为e
        public void set(int index, E e) {
            data[index] = e;
            set(0, 0, data.length - 1, index, e);
        }
        
        // 在treeIndex为根的线段树中[l...r]的范围里，更新index处的节点值为e
        private void set(int treeIndex, int l, int r, int index, E e) {
            if(l == r) {
                tree[treeIndex] = e;
                return;
            }
            int mid = l + ((r - l) >> 1);
            int leftChildIndex = getLeftChildIndex(treeIndex);
            int rightChildIndex = getRightChildIndex(treeIndex);
            if(index <= mid) {
                set(leftChildIndex, l, mid, index, e);
            } else { // (index > mid + 1) 
                set(rightChildIndex, mid + 1, r, index, e);
            }
            tree[treeIndex] = merger.merge(tree[leftChildIndex], tree[rightChildIndex]);
        }
        
    }
    private SegmentTree<Integer> segmentTree;
    private Integer[] data;
    public NumArray_v2(int[] nums) {
        data = new Integer[nums.length];
        for(int i = 0; i < nums.length; i++) {
            data[i] = nums[i];
        }
        if(nums.length > 0) {
            segmentTree = new SegmentTree(data, new Merger<Integer>() {
                @Override
                public Integer merge(Integer a, Integer b) {
                    return a + b;
                }
            });
        }
    }
    
    public void update(int i, int val) {
        if(segmentTree == null) {
            throw new RuntimeException("构建线段树的数组长度为0，线段树为空！");
        }
        segmentTree.set(i, val);
    }
    
    public int sumRange(int i, int j) {
        if(segmentTree == null) {
            throw new RuntimeException("构建线段树的数组长度为0，线段树为空！");
        }
        return segmentTree.query(i, j);
    }
    
    public static void main(String[] args) {
        int[] nums = {-2, 0, 3, -5, 2, -1};
        NumArray_v2 obj = new NumArray_v2(nums);
        System.out.println(obj.sumRange(2, 5));
        obj.update(2, 4);
        System.out.println(obj.sumRange(2, 5));
    }
}